<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>
</head>

<body>
    <div class="container">
        <!-- Logo -->
        <img src="./images/taobao_logo.png" alt="" class="logo" />

        <div class="box">
            <!-- tab 栏 -->
            <div class="tabs">
                <div class="tab-active">宝贝</div>
                <div>店铺</div>
            </div>

            <!-- 搜索区域（搜索框和搜索按钮） -->
            <div class="search-box">
                <input id="ipt" type="text" class="ipt" placeholder="请输入要搜索的内容" />
                <button class="btnSearch">搜索</button>
            </div>

            <!-- 搜索建议列表 -->
            <div id="suggest-list"></div>
        </div>
    </div>

    <script>
        $(function() {

            var timer = null

            // 定义全局缓存对象
            var cache = {}

            function debounceSearch(kw) {
                timer = setTimeout(function() {
                    getList(kw)
                }, 500)
            }

            $('#ipt').on('keyup', function() {
                clearTimeout(timer)

                var keyword = $(this).val().trim()

                if (keyword.length <= 0) {
                    return
                }

                // 判断是否有缓存
                if (cache[keyword]) {
                    return readerHtml(cache[keyword])
                }

                debounceSearch(keyword)
            })

            // 发送ajax的方法
            function getList(kw) {
                $.ajax({
                    url: `https://suggest.taobao.com/sug?q=${kw}`,
                    dataType: 'jsonp',
                    success: function(res) {
                        // console.log(res);
                        // 缓存
                        cache[kw] = res

                        readerHtml(res)
                    }
                })
            }

            // 生成页面的方readerHtml法
            function readerHtml(res) {
                var html = ''

                $.each(res.result, function(index, item) {
                    html += `
                        <div class="suggest-item">${item[0]}</div>
                    `
                })

                $('#suggest-list').append(html).show()

            }
        })
    </script>
</body>

</html>